<template>
  <OrderTabContainer :btn1-callback="save" label1="Save" :disable="readOnly" :isNeedScroll="false">
    <slot></slot>
    <div class="bg-blue-1 q-pa-md card-radius">
      <q-card>
        <q-card-section>
          <i class=""
            >Please go to Part Detail process fitment/defitment for fault
            equipment</i
          >
        </q-card-section>

        <div class="row q-pa-md">
          <div class="col-3 fal">
            Test Result.<span style="color: red">*</span>
          </div>
          <q-select
            class="input-css col-5"
            :options="['FF', 'Within spec.', 'NAF']"
            v-model="state.data.test_result"
            :dense="true"
            :readonly="readOnly"
            lazy-rules
            hide-bottom-space
            :rules="[(val) => val.length > 0 || 'Require field']"
          />
        </div>

        <q-card-section class="row fal">
          <div class="col-3 fal">Maintenance Details:</div>
          <q-input
            class="input-css col-5"
            v-model="state.data.maintenance_details"
            :dense="true"
            :readonly="readOnly"
            lazy-rules
            hide-bottom-space
          />
        </q-card-section>

        <q-card-section class="row fal">
          <div class="col-3">Repairing Details:</div>
          <q-select
            :readonly="readOnly"
            class="col-5 input-css"
            :dense="true"
            :options="repairingOpts"
            v-model="state.data.repair_details"
          >
          </q-select>
        </q-card-section>

        <q-card-section class="row justify-start" v-if="isMyParent && faultEp">
          <div class="col-3">Fault Equipment:</div>
          <div
            style="
              border: 1px solid rgb(185, 185, 185);
              padding: 0.5rem;
              width: 250px;
            "
          >
            <template v-if="state.data.fault_equipment_JSON_OBJ">
              <div
                v-for="(item, index) in state.data.fault_equipment_JSON_OBJ"
                :key="index"
              >
                <q-checkbox
                  dense
                  :disable="readOnly"
                  :model-value="item"
                  :label="index"
                  @update:model-value="(v, e) => updateFaultList(index, v)"
                  color="primary"
                />
              </div>
            </template>
          </div>
        </q-card-section>

        <q-card-section class="row fal" v-if="failsys">
          <div class="col-3">Failure Symptom:</div>
          <q-input
            :readonly="readOnly"
            class="col-5 input-css"
            :dense="true"
            v-model="state.data.failure_symptom"
          ></q-input>
        </q-card-section>
        <q-card-section class="row fal" v-if="action">
          <div class="col-3">Action:</div>
          <q-select
            :readonly="readOnly"
            class="col-5 input-css"
            :dense="true"
            v-model="state.data.actions"
            :options="actionOpts"
          ></q-select>
        </q-card-section>
        <q-card-section v-if="remark" class="row fal">
          <div class="col-3">Remarks:</div>
          <q-input
            :readonly="readOnly"
            class="col-5 input-css"
            :dense="true"
            v-model="state.data.remarks"
          ></q-input>
        </q-card-section>
        <q-card-section class="row fal" v-if="mainType">
          <div class="col-3">Maintenance Type:</div>
          <q-select
            :readonly="readOnly"
            class="col-5 input-css"
            :dense="true"
            :options="maintenance_typeOpts"
            v-model="state.data.maintenance_type"
          ></q-select>
        </q-card-section>
        <q-card-section class="row fal" v-if="nnf">
          <div class="col-3">Repeat Within 6 months? :</div>
          <q-select
            :readonly="readOnly"
            class="col-5 input-css"
            :dense="true"
            :options="['YES', 'NO']"
            v-model="state.data.repeat_within_six_months"
          ></q-select>
        </q-card-section>
        <q-card-section class="row fal" v-if="spare">
          <div class="col-3">Enough spare part?:</div>
          <q-select
            :readonly="readOnly"
            class="col-5 input-css"
            :dense="true"
            :options="['YES', 'NO']"
            v-model="state.data.spare_part"
          ></q-select>
        </q-card-section>
        <q-card-section class="row fal">
          <div class="col-3">Delivery to:</div>
          <q-select
            :readonly="readOnly"
            class="col-5 input-css"
            :dense="true"
            :options="inputOptionStore.data.depot"
            v-model="state.data.delivery_to"
          ></q-select>
        </q-card-section>
        <q-card-section class="row fal" v-if="scrapped">
          <div class="col-5">To Be Scrapped:</div>
          <q-checkbox
            dense
            :disable="readOnly"
            v-model="state.data.scrapped"
            :label="''"
            color="primary"
          />
        </q-card-section>
      </q-card>
    </div>
  </OrderTabContainer>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue';
import { getStatusColor } from 'src/utils/getPublic';
import OrderTabContainer from '../container/OrderTabContainer.vue';
import { FinalCheckForm, Parts } from 'src/services/type';
import {
  getFinalCheckForm,
  getOrderDetail,
  getOrderParts,
  updateOrderFinalCheckForm,
} from 'src/services/repairService';
import { useQuasar } from 'quasar';
import { useInputOption } from 'src/stores/inputOptionStore';

const inputOptionStore = useInputOption();
inputOptionStore.init()

const props = defineProps<{
  orderId: number;
  stockCode: string;
  serialNo: string;
  isParent?: boolean;
  mode?: 'report';
}>();

const isMyParent = ref(false);
if (props.isParent) {
  isMyParent.value = true;
}

const q = useQuasar();

const state = reactive<{
  data: FinalCheckForm;
}>({
  data: {
    repair_order_id: 0,
    repair_details: '',
    fault_equipment: '',
    fault_equipment_JSON_OBJ: {},
    failure_symptom: '',
    actions: '',
    remarks: '',
    maintenance_type: '',
    delivery_to: '',
    scrapped: false,
    deleted: false,
    repeat_within_six_months: '',
    spare_part: '',
    test_result: '',
    maintenance_details: '',
  },
});

const faultEp = ref(false);
const failsys = ref(false);
const action = ref(false);
const remark = ref(false);
const mainType = ref(false);
const scrapped = ref(false);
const nnf = ref(false);
const spare = ref(false);
watch(
  () => state.data.repair_details,
  (repair_details) => {
    faultEp.value = false;
    failsys.value = false;
    action.value = false;
    remark.value = false;
    mainType.value = false;
    scrapped.value = false;
    if (repair_details == 'NOT A FAULT (E.G PM, IGI)') {
      remark.value = true;
    }
    if (repair_details == 'FAULT CANNOT BE REPEATED (CM)') {
      failsys.value = true;
      mainType.value = true;
      // scrapped.value = true;
    }
    if (repair_details == 'FAULT FOUND (CM)') {
      faultEp.value = true;
      failsys.value = true;
      action.value = true;
      remark.value = true;
      scrapped.value = true;
    }
  }
);

watch(
  () => state.data.maintenance_type,
  (maintenance_type) => {
    if (maintenance_type == 'NFF') {
      nnf.value = true;
    } else {
      nnf.value = false;
      state.data.repeat_within_six_months = '';
    }
  }
);

watch(
  () => state.data.repeat_within_six_months,
  (repeat_within_six_months) => {
    console.log('repeat_within_six_months', repeat_within_six_months);
    
    if (repeat_within_six_months == 'YES') {
      spare.value = true;
    } else {
      spare.value = false;
      state.data.spare_part = '';
    }
  }
);

watch(
  () => state.data.actions,
  (actions) => {
    if (
      actions == 'COMPONENT FOUND FAULTY & REPAIR' ||
      actions == 'COMPONENT FOUND FAULTY & DISPOSAL/SCRAP'
    ) {
      console.log(state.data.remarks);

      if (state.data.remarks == ''){
        state.data.remarks = 'Components: ';
      }else{
        return
      }
    }
    if (actions == 'SENT FOR REPAIR') {
      if (state.data.remarks == ''){
        state.data.remarks = 'PO/Pcard order no.: ';
      }else{
        return
      }
    }
  }
);
const repairingOpts = [
  '----------',
  'NOT A FAULT (E.G PM, IGI)',
  'FAULT CANNOT BE REPEATED (CM)',
  'FAULT FOUND (CM)',
];
const actionOpts = [
  '----------',
  'COMPONENT FOUND FAULTY & REPAIR',
  'COMPONENT FOUND FAULTY & DISPOSAL/SCRAP',
  'SENT FOR REPAIR',
];
const maintenance_typeOpts = [
  '----------',
  'Preventive Measure',
  'Health Check',
  'Interface Issues',
  'Other Fault',
  'NFF',
];

const readOnly = ref(false);

async function save() {
  if (state.data.repair_details=='NOT A FAULT (E.G PM, IGI)'){
    state.data = {
      ...state.data,
      fault_equipment:'',
      fault_equipment_JSON_OBJ: {},
      failure_symptom: '',
      actions: '',
      maintenance_type: '',
      scrapped: false,
      repeat_within_six_months: '',
      spare_part: '',
    }
  }
  if (state.data.repair_details=='FAULT CANNOT BE REPEATED (CM)'){
    console.log('hellp');
    
    state.data = {
      ...state.data,
      fault_equipment:'',
      fault_equipment_JSON_OBJ: {},
      actions: '',
      remarks:'',
      scrapped: false,
    }
  }
  if (state.data.repair_details=='FAULT FOUND (CM)'){
    state.data = {
      ...state.data,
      maintenance_type: '',
      repeat_within_six_months: '',
      spare_part: '',
    }
  }

  state.data.fault_equipment = JSON.stringify(
    state.data.fault_equipment_JSON_OBJ
  );
  console.log('update', state.data);
  
  const res = await updateOrderFinalCheckForm(state.data);
  if (res.data) {
    q.notify({
      message: 'Success',
      color: 'positive',
    });
    init();
  }
}

function updateFaultList(index: string, value: boolean) {
  state.data.fault_equipment_JSON_OBJ[index] = value;
}

async function initEquipmentList() {
  const res = await getOrderParts(props.orderId);
  let ret: { [k: string]: boolean } = {};
  if (Object.keys(state.data.fault_equipment_JSON_OBJ).length == 0) {
    res.data.forEach((v: Parts) => {
      if (v.description.length) ret[v.description] = false;
    });
    state.data.fault_equipment_JSON_OBJ = { ...ret };
  }
}
async function initJobStatus() {
  const res = await getOrderDetail(props.orderId);
  if (res.data) {
    if ( props.mode == 'report'){
        readOnly.value = false;
    }
    else if (
      res.data.status == 'COMPLETE' ||
      res.data.status == 'COMPLETE*' ||
      res.data.status == 'CHECKOUT' 
    ) {
      readOnly.value = true;
    }
  }
}

async function init() {
  const res = await getFinalCheckForm(props.orderId);
  console.log(res.data);
  
  state.data = res.data;
  state.data.repair_order_id = props.orderId;
  try {
    state.data.fault_equipment_JSON_OBJ = JSON.parse(
      state.data.fault_equipment
    );
    state.data.repair_order_id = res.data.repair_order;
  } catch (err) {
    console.log(err);
    state.data.fault_equipment_JSON_OBJ = {};
  }
  initJobStatus();
  initEquipmentList();
}
init();
</script>
<style scoped>
table {
  border-collapse: collapse;
  table-layout: fixed;
}

td {
  padding: 0.5rem;
}

table thead tr th {
  border-bottom: 1px solid #d9d9d9;
}

table tbody tr {
  border-top: 1px solid #d9d9d9;
  border-bottom: 1px solid #d9d9d9;
}
</style>
